<template>
	<view class="payment-container">
		<view class="form-section">
			<view class="form-item">
				<text class="form-label">关联项目 <text class="required">*</text></text>
				<picker @change="onProjectChange" :value="projectIndex" :range="projectList">
					<view class="picker-input">
						<text>{{ projectList[projectIndex] }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
		</view>
		
		<view class="form-section">
			<view class="form-item">
				<text class="form-label">关联费用合同</text>
				<input class="form-input" v-model="contractNumber" placeholder="请输入关联合同编号" />
			</view>
			
			<view class="form-item">
				<text class="form-label">收款人全称</text>
				<input class="form-input" v-model="payeeFullName" placeholder="请输入收款人全称" />
			</view>
			
			<view class="form-item">
				<text class="form-label">收款账户</text>
				<input class="form-input" v-model="accountNumber" placeholder="请输入收款账户" />
			</view>

			<view class="form-item">
				<text class="form-label">开户银行</text>
				<input class="form-input" v-model="bankName" placeholder="请输入开户银行" />
			</view>

			<view class="form-item">
				<text class="form-label">付款金额</text>
				<input class="form-input" type="digit" v-model="amount" placeholder="请输入付款金额" />
			</view>
			
			<view class="form-item">
				<text class="form-label">付款用途</text>
				<picker @change="onPaymentTypeChange" :value="paymentTypeIndex" :range="paymentTypes">
					<view class="picker-input">
						<text>{{ paymentTypes[paymentTypeIndex] }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">付款方式</text>
				<picker @change="onPaymentMethodChange" :value="paymentMethodIndex" :range="paymentMethods">
					<view class="picker-input">
						<text>{{ paymentMethods[paymentMethodIndex] }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">付款日期</text>
				<DateTimePicker v-model="paymentDate" mode="hour" />
			</view>

			<view class="form-item textarea-item">
				<text class="form-label">付款费用明细</text>
				<textarea 
					class="form-textarea" 
					v-model="reason" 
					placeholder="请详细填写付款费用明细"
					maxlength="300"
				></textarea>
				<text class="char-count">{{ reason.length }}/300</text>
			</view>			

			<view class="form-item">
				<UploadAttachments 
					style="width: 100%;"
					v-model="uploadedFiles"
					label="附件材料"
					:max-count="5"
					:file-types="['jpg', 'jpeg', 'png']"
				/>
			</view>
		</view>

		<!-- 审批流程 -->
		<view class="approval-section">
			<text class="section-title">审批流程</text>
			<view class="approval-steps">
				<view v-if="approvalSteps.length > 0">
					<view class="approval-step" v-for="(step, index) in approvalSteps" :key="index">
						<view class="step-header">
							<view class="step-avatar">
								<text class="avatar-text">{{ step.user_name.charAt(0) }}</text>
							</view>
							<view class="step-info">
								<text class="step-name">{{ step.user_name }}</text>
								<text class="step-position">{{ step.position }}</text>
							</view>
							<text v-if="!isNew" :class="['step-status', getStepStatusClass(step.status)]">
								{{ getStepStatusText(step.status) }}
							</text>
						</view>
						<view class="step-content" v-if="step.comment">
							<text class="step-comment">{{ step.comment }}</text>
							<text class="step-time">{{ step.update_time }}</text>
						</view>
					</view>
				</view>
				<view v-else class="empty-approval">
					<view class="empty-icon">!</view>
					<text class="empty-text">付款流程未定义，请联系管理员</text>
				</view>
			</view>
		</view>

		<view class="submit-section">
			<button class="submit-button" @tap="submitPayment" :disabled="!canSubmit()">
				{{ approvalSteps.length > 0 ? '提交' : '付款流程未定义，无法提交' }}
			</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getProjects, getCurrentToken, getCurrentUser } from '@/common/auth'
import config from '@/common/config'
import DateTimePicker from '@/components/DateTimePicker.vue'
import UploadAttachments from '@/components/UploadAttachments.vue'
import { paymentApi, workflowUtils } from '@/common/api'
import { uploadFile as uploadSingleFile, uploadAttachments, formatFileSize } from '@/common/upload'

// TypeScript interfaces
interface PaymentFile {
	name: string
	url: string
	path: string
	size: string
	type: string
}

interface ApprovalStep {
	position: string
	user_name: string
	user_id: string
	status: string
	comment?: string
	update_time?: string
}

interface Project {
	project_id: string
	project_name: string
}

// 获取当前用户信息
const currentUser = getCurrentUser()

const paymentTypes = ref<string[]>(['货款', '服务费', '差旅费', '办公费用', '其他'])
const paymentTypeIndex = ref<number>(0)
const paymentMethods = ref<string[]>(['银行转账', '现金支付', '微信支付', '支付宝'])
const paymentMethodIndex = ref<number>(0)
const payeeFullName = ref<string>('')
const amount = ref<string>('')
const reason = ref<string>('')
const specifications = ref<string>('')
const contractNumber = ref<string>('')
const accountNumber = ref<string>('')
const bankName = ref<string>('')
const paymentDate = ref<string>('')
const uploadedFiles = ref<PaymentFile[]>([])
const approvalSteps = ref<ApprovalStep[]>([])
const isNew = ref<boolean>(true)
const workflow_id = ref<number>(0)
const region_company = ref<string>('')

// 项目相关
const projects = getProjects() as Project[]
const projectIndex = ref<number>(0)
const projectList = ref<string[]>(projects.map((project) => project.project_name))

// 格式化日期
const formatDate = (date: Date): string => {
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	return `${year}/${month}/${day} ${hours}:${minutes}`
}

// 获取步骤状态样式
const getStepStatusClass = workflowUtils.getStepStatusClass

// 获取步骤状态文本
const getStepStatusText = workflowUtils.getStepStatusText

const onPaymentTypeChange = (e: any) => {
	paymentTypeIndex.value = e.detail.value
}

const onPaymentMethodChange = (e: any) => {
	paymentMethodIndex.value = e.detail.value
}

const onProjectChange = (e: any) => {
	projectIndex.value = e.detail.value
	// 切换项目时重新加载审批人
	loadApprovers()
}

const canSubmit = (): boolean => {
	return !!payeeFullName.value &&
		!!amount.value && 
		!!reason.value.trim() && 
		!!accountNumber.value && 
		!!paymentDate.value &&
		approvalSteps.value.length > 0
}



// 加载审批人列表
const loadApprovers = async () => {
	try {
		if (projects[projectIndex.value]) {
			uni.showLoading({
				title: '加载审批人...'
			})
			
			const projectId = projects[projectIndex.value].project_id;
			
			// 使用与请假相同的API获取审批人，但类型为"payment"
			const res = await paymentApi.getApprovers(projectId, "expense-payment");
			uni.hideLoading()

			if (res.success && res.data.length > 0) {
				const approvalWorkflow = res.data[0];
				workflow_id.value = approvalWorkflow.id;
				region_company.value = approvalWorkflow.region_company;
				approvalSteps.value = approvalWorkflow.approval_process.map((approver: any) => ({
					position: approver.approver_position || '审批人',
					user_name: approver.approver_name,
					user_id: approver.approver_id
				}))
			} else {
				console.log('未找到付款审批流程')
				approvalSteps.value = []
			}
		}
	} catch (error) {
		uni.hideLoading()
		console.error('获取审批人列表失败:', error)

		uni.showToast({
			title: '获取审批人失败',
			icon: 'none',
			duration: 2000
		})
		
		approvalSteps.value = []
	}
}

const submitPayment = async () => {
	if (!canSubmit()) {
		uni.showToast({
			title: '请完善申请信息',
			icon: 'none'
		})
		return
	}

	uni.showLoading({
		title: '提交中...'
	})

	try {
		// 准备提交的数据（先不包含附件）
		const submitData = {
			payeeFullName: payeeFullName.value,
			amount: amount.value,
			paymentType: paymentTypes.value[paymentTypeIndex.value],
			paymentMethod: paymentMethods.value[paymentMethodIndex.value],
			paymentDate: paymentDate.value,
			contractNumber: contractNumber.value,
			reason: reason.value,
			specifications: specifications.value,
			accountNumber: accountNumber.value,
			bankName: bankName.value,
			submitTime: new Date().toISOString(),
			region_company: region_company.value,
			workflow_id: workflow_id.value,
			project_id: projects[projectIndex.value].project_id
		}

		console.log('提交的付款数据:', submitData)

		uni.showLoading({
			title: '提交申请中...'
		})

		// 先提交表单数据
		const res = await paymentApi.apply(submitData)

		if (!res.success) {
			uni.hideLoading()
			uni.showToast({
				title: res.message || '提交失败',
				icon: 'none',
				duration: 3000
			})
			return
		}

		// 获取申请ID
		const { expense_payment_id, approval_instance_id } = res.data

		// 如果有附件，再上传附件
		if (uploadedFiles.value.length > 0) {
			uni.showLoading({
				title: '上传附件中...'
			})

			try {
				// 转换文件格式
				const files = uploadedFiles.value.map(file => ({
					path: file.path,
					name: file.name,
					size: parseInt(file.size) || 0,
					type: file.type
				}));

				// 使用通用上传工具上传文件，支持并行上传
				const uploadedAttachments = await uploadAttachments(				
					files,
					true, // 并行上传
					{
						type: "attachment",
						relation_id: expense_payment_id, // 传递申请ID
						approval_instance_id: approval_instance_id, // 传递审批实例ID
						relation_type: "expense-payment" // 传递申请类型
					},
					(current, total) => {
						// 更新上传进度
						uni.showLoading({
							title: `上传中 ${current}/${total}`
						});
					}
				);

				// 如果需要，可以调用更新附件API
				if (uploadedAttachments.length > 0) {
					const attachments = uploadedAttachments.map(file => ({
						path: file.path,
						size: String(file.size),
						type: file.type,
						url: file.url
					}));

					// 可选：调用更新附件API
					// await paymentApi.updateAttachments(payment_id, attachments);
				}
			} catch (error: any) {
				console.error('文件上传失败:', error)
				uni.showToast({
					title: '部分附件上传失败，请在详情页重新上传',
					icon: 'none',
					duration: 2000
				})
				// 继续流程，不影响已提交的申请
			}
		}

		uni.hideLoading()
		console.log('提交成功:', res)

		uni.showToast({
			title: '申请提交成功',
			icon: 'success'
		})

		// 清空表单
		payeeFullName.value = ''
		amount.value = ''
		reason.value = ''
		specifications.value = ''
		accountNumber.value = ''
		bankName.value = ''
		paymentDate.value = ''
		contractNumber.value = ''
		uploadedFiles.value = []
		paymentTypeIndex.value = 0
		paymentMethodIndex.value = 0

		// 跳转到首页
		uni.switchTab({
			url: '/pages/home/home'
		})
	} catch (error: any) {
		uni.hideLoading()
		console.error('提交失败:', error)
		uni.showToast({
			title: error.message || '网络错误，请稍后重试',
			icon: 'none',
			duration: 3000
		})
	}
}

// 页面加载时初始化
onLoad(() => {
	// 加载审批人
	loadApprovers()
})
</script>

<style scoped>
.payment-container {
	padding: 0;
	background-color: #f5f6fa;
	min-height: 100vh;
}

.form-section {
	background: white;
	border-radius: 0;
	padding: 0;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.form-item {
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
	margin-bottom: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	min-height: 88rpx;
}

.form-item:last-child {
	border-bottom: none;
}

.form-item.textarea-item {
	flex-direction: column;
	align-items: stretch;
	min-height: auto;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 0;
	display: block;
	flex-shrink: 0;
}

.required {
	color: #f44336;
	font-size: 28rpx;
}

.optional {
	color: #999;
	font-size: 28rpx;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	min-height: 48rpx;
	flex: 1;
	max-width: 400rpx;
}

.form-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	min-height: 48rpx;
	flex: 1;
	max-width: 400rpx;
	text-align: right;
}

.picker-arrow {
	color: #999;
	margin-left: 8rpx;
}

.form-textarea {
	width: 100%;
	box-sizing: border-box;
	min-height: 120rpx;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	font-size: 28rpx;
	line-height: 1.5;
	margin-top: 16rpx;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
	display: block;
}

.approval-section {
	background: white;
	border-radius: 0;
	padding: 32rpx;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.approval-steps {
	margin-top: 24rpx;
}

.approval-step {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
}

.step-header {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.step-avatar {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #2B5BA1;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
	margin-right: 16rpx;
}

.avatar-text {
	color: white;
}

.step-info {
	flex: 1;
}

.step-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
}

.step-position {
	font-size: 24rpx;
	color: #666;
}

.step-status {
	font-size: 24rpx;
	padding: 4rpx 12rpx;
	border-radius: 8rpx;
}

.step-status.pending {
	color: #2196f3;
	background: #e3f2fd;
}

.step-status.approved {
	color: #4caf50;
	background: #e8f5e9;
}

.step-status.rejected {
	color: #f44336;
	background: #ffebee;
}

.step-status.canceled {
	color: #9e9e9e;
	background: #f5f5f5;
}

.step-content {
	margin-top: 16rpx;
	padding-top: 16rpx;
	border-top: 1rpx solid #eee;
}

.step-comment {
	font-size: 28rpx;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.step-time {
	font-size: 24rpx;
	color: #999;
}

.submit-section {
	padding: 32rpx;
	margin-bottom: 0;
}

.submit-button {
	width: 100%;
	background: #2B5BA1;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 6rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.submit-button[disabled] {
	background: #ccc;
}

:deep(.error .picker-input) {
	border-color: #f44336;
	background-color: #fff5f5;
}

:deep(.picker-input) {
	border: none !important;
	background: transparent !important;
	padding: 0 !important;
	justify-content: flex-end !important;
	max-width: 400rpx;
}

:deep(.picker-text) {
	text-align: right !important;
	color: #333 !important;
}

:deep(.picker-text.placeholder) {
	color: #999 !important;
}

:deep(.picker-arrow) {
	margin-left: 8rpx !important;
}

.empty-approval {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 40rpx 24rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	text-align: center;
}

.empty-icon {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #ff9800;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 16rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #666;
}
</style> 